package com.kcht.rd30.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kcht.rd30.entity.AbnormalDetectionEntity;
import com.kcht.rd30.entity.TimeCalibrationEntity;
import com.kcht.rd30.mapper.IAbnormalDetectionMapper;
import com.kcht.rd30.service.IAbnormalDetectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
public class AbnormalDetectionManager extends ServiceImpl<IAbnormalDetectionMapper, AbnormalDetectionEntity> implements IAbnormalDetectionService {
    private Map<String,AbnormalDetectionHandler> handlerMap=new HashMap<>();
    @Autowired
    private IAbnormalDetectionMapper abnormalDetectionMapper;
    @Value("${detection.duration:60}")
    private Integer duration;
    @Value("${detection.report-url:null}")
    private String reportUrl;

    /**
     * 监听ApplicationContext初始化或刷新的事件
     * 启动时执行此方法
     */
    @EventListener
    public void loadAllIP(ContextRefreshedEvent event){
        Set<String> ips = abnormalDetectionMapper.findAllIp();
        if(ips==null)return;
        for (String ip : ips) {
            handlerMap.put(ip,new AbnormalDetectionHandler(ip,reportUrl,duration,abnormalDetectionMapper));
        }
    }

    //todo 增加时注意判断是否重复ip
    //todo 更新时注意,不能更新ip
    //todo 删除时注意先closeThread
}
